﻿
CREATE FUNCTION [dbo].[NoteDateDue](
	@StatusID int
)RETURNS datetime WITH SCHEMABINDING AS BEGIN

IF ISNULL(@StatusID,0) = 0 SELECT @StatusID = ID FROM dbo.t_State WHERE TableName = 't_Note' AND ParentID = 0
DECLARE @Hours int SET @Hours = CONVERT(int,dbo.fs_StateParamValue(@StatusID,'NextDateDue_Hours'))
DECLARE @Date datetime
SELECT @Date =
	CASE WHEN @Hours > 0 
			 THEN DATEADD(hh,@Hours,GETDATE())
			 ELSE dbo.Today(GETDATE())
	END +COALESCE(CONVERT(int,dbo.fs_StateParamValue(@StatusID,'NextDateDue_Days')),
																										CONVERT(int,dbo.fs_StateParamValue(SP.ID,'NextDateDue_Days')),3)
FROM dbo.t_State S 
INNER JOIN dbo.t_State SP ON SP.ID = S.ParentID
WHERE S.ID = @StatusID

IF DATEPART(hh,@Date) = 0 SET @Date = DATEADD(hh,9,@Date)

RETURN @Date

END


